<template>
	<view class="chart-container">
		<u-toast ref="uToast"></u-toast>
		<view class="tip-icon-container">
			<view class="tip-left">
				<tip :isYellow="true" :message="accountbookName" @showSelectTimeFunction="changeFlag('isAcconutBookListFlag', true)"></tip>
			</view>
			<view class="inner-month-container">
				<view class="inner-month-container-last-month">
					<view class="inner-month-container-last-month-icon-bgc-container" @click="changeMonth(-1)">
						<view class="inner-month-container-last-month-icon-item iconfont icon-xiangzuo"></view>
					</view>
				</view>
				<view class="inner-month-container-this-month">{{month}}</view>
				<view class="inner-month-container-next-month">
					<view class="inner-month-container-next-month-icon-bgc-container" @click="changeMonth(1)">
						<view class="inner-month-container-next-month-icon-item iconfont icon-xiangyou1"></view>
					</view>
				</view>
			</view>
			<view class="right-icon-container">
				<view class="right-icon-container-type-icon-bgc-container">
					<view class="right-icon-container-type-icon-item">月</view>
					<view class="right-icon-container-type-icon-down-icon iconfont icon-xiangxia1"></view>
				</view>
			</view>
		</view>
		<view class="line-chart-container">
			<view class="charts-box">
				<qiun-data-charts :margin="0" :show="true" type="mix" :canvas2d="true" canvasId="four_c" :resshow="delayload"
					:opts="optsLine" :chartData="TrendData" :ontouch="true" />
			</view>
		</view>
		<view class="pie-chart-container">
			<view class="pie-chart-title-container">
				<view class="pie-chart-title-left-container">
					支出 TOP 5
				</view>
				<view class="pie-chart-title-right-select-type">
					<view :class="['pie-chart-title-right-select-type-pie', 'iconfont', 'icon-yuanhuantu', {'icon-purple': showPieChart}]" @click="showChartPie(true)"></view>
					<view :class="['pie-chart-title-right-select-type-bar', 'iconfont', 'icon-tubiaozhuxingtu', {'icon-purple': !showPieChart}]" @click="showChartPie(false)"></view>
				</view>
			</view>
			<view class="pie-charts-box" v-if="showPieChart">
				<qiun-data-charts type="ring" :opts="opts2" :chartData="pieVoList" />
			</view>
			<view class="bar-charts-box" v-if="!showPieChart">
				<my-progress-bar :categoryList="barVoList"></my-progress-bar>
				<!-- <progress-bar :isRank="true" :content="barVoList" /> -->
			</view>
		</view>
		<view class="budget-bar-container">
			<budget-bar :categoryList="categoryList"></budget-bar>
		</view>
		<!-- 账本列表 -->
		<u-popup :show="isAcconutBookListFlag" :round="20" mode="top" @close="changeFlag('isAcconutBookListFlag', false)" @open="changeFlag('isAcconutBookListFlag', true)">
			<account-book-list @selectAccountBook="selectAccountBook" :accountBookList="accountBooks" @closeBtn="changeFlag('isAcconutBookListFlag', false)"></account-book-list>
			<!-- <account-book-list @closeBtn="changeFlag('isAcconutBookListFlag', false)"></account-book-list> -->
		</u-popup>
	</view>
</template>

<script>
	import accountBookList from '@/components/account-book-list/account-book-list.vue';
	import progressBar from './components/progress-bar/progress-bar.vue';
	import myProgressBar from './components/my-progress-bar/my-progress-bar.vue';
	import budgetBar from '@/components/budget-bar/budget-bar.vue';
	export default {
		components: {
			progressBar, budgetBar, accountBookList, myProgressBar
		},
		data() {
			return {
				lineXSet: [],									// X轴数据
				categoryList: [],								// 预算数据
				barVoList: [],									// 柱形数据
				lineVoList: [],									// 折现数据
				pieVoList: {},									// 饼图数据
				year: '',										// 年份
				accountBooks: [],								// 账本数据
				accountBookIndex: 0,							// 账本索引
				currentTime: '',								// 当前时间(是切换后的)
				month: '',										// 中间的月份 （如果是当前月时不显示年份，反之显示）
				currentMonth: '',								// 当前月份(不会修改)
				month: '',										// 显示月份
				isAcconutBookListFlag: false,					// 账本弹框
				showPieChart: true, 							// 是否显示圆环图 false显示条形图
				accountbookName: '',
				delayload: false, 								// 延时加载图表，否则会出现图表加载完后定位错乱
				TrendData: {},
				chartData2: {},
				optsLine: {
					touchMoveLimit: 24,
					enableScroll: true,
					legend: {},
					xAxis: { disableGrid: true, scrollShow: true, itemCount: 7},
					yAxis: {data:[{position: 'left',title: '',min: 0, unit: '', fontColor: this.themePurpleColor, titleColor: 'red'}]},
				},
				opts2: {
					rotate: false,
					rotateLock: false,
					color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: [5, 5, 5, 5],
					dataLabel: true,
					legend: {
						show: true,
						position: "right",
						lineHeight: 25
					},
					title: {
						name: "",
						fontSize: 15,
						color: "white"
					},
					subtitle: {
						name: "",
						fontSize: 25,
						color: "white"
					},
					extra: {
						ring: {
							ringWidth: 20,
							activeOpacity: 0.5,
							activeRadius: 10,
							offsetAngle: 0,
							labelWidth: 15,
							border: true,
							borderWidth: 3,
							borderColor: "#FFFFFF"
						}
					}
				},
				data: [],
			}
		},
		onLoad() {
			this.initMonth( () => this.getChartData());
		},
		mounted() {
			// 模拟从服务器获取数据
			// this.getServerData();
			// this.getData();
			// this.getTrendData();

			// 真实数据
			// this.getChartData();
		},
		methods: {
			/** 选择账本回调
			 * @param {Object} item 选中的账本
			 * @param {Object} index 索引
			 */
			selectAccountBook(item, index1) {
				if (!this.accountBooks) {
					return;
				}
				this.accountBooks.forEach((item, index) => item.selected = index == index1);
				this.changeFlag('isAcconutBookListFlag', false);
				this.accountBookIndex = index1;
				this.accountbookName = this.accountBooks[index1].name;
				// this.bill.accountBookId = item.id;
				// this.bill.accountBookName = item.name;
				// this.categoryList = [];
				// this.categoryList.push(...this.accountBooks[this.accountBookIndex].incomeCategoryList);
				// this.categoryList.push(...this.accountBooks[this.accountBookIndex].payCategoryList);
				// 选择账本id后请求数据
				this.init();
			},
			/**
			 * 查询全部的账本 由于需要此方法先执行，然后再执行init()，所以两个子方法中也必须加上（函数名前 + async，请求前 + await），
			 * 最后一个不加没关系，因为它后面没有被依赖。如果还有方法需要拿到init后的数据来请求的话就需要了
			 */
			async getAccountBookList() {
				var that = this;
				await that.$req.getAccountBookList().then(res => {
					res.data.forEach(item => console.log(item.selected))
					if (res.success) {
						that.accountBooks = res.data;
						that.accountbookName = that.accountBooks[that.accountBookIndex].name;
					} else {
						that.accountBooks = [];
						that.errorTips(that.$refs.uToast, res.message, null);
					}
				})
			},
			/**
			 * 初始化各个图标数据
			 */
			async init() {
				var that = this;
				var params = "parentId=" + that.accountBooks[that.accountBookIndex].id;
				if (this.month) {
					var monthYearArr = this.month.split("-");
					params += "&year=" + monthYearArr[0] + "&month=" + monthYearArr[1];
				}
				that.$req.getCharts(params).then(res => {
					if (res.success) {
						that.pieVoList = {series: [{data: res.data.pieVoList}]};
						that.barVoList = res.data.barVoList;
						that.categoryList = res.data.categoryList;
						that.lineVoList = res.data.lineVoList;
						that.lineXSet = res.data.lineXSet;
						var series = res.data.lineVoList;
						// x轴必须是这个名字，否则会报错
						var categories = res.data.lineXSet;
						that.TrendData = {categories, series,
								"yAxis": [{
									"calibration": true,
									"position": "left",
									"min": 0,
									"max": 3000,
									"title": "",
									"titleFontSize": 20,
									"unit": "万",
									"tofix": 0
								}],
								"targetAdd": "9%"
							}
					} else {
						that.errorTips(that.$refs.uToast, res.message, null);
					}
				})
			},
			/**
			 * 获取页面数据，等待先查询账本数据，拿到账本数据后根据索引取出账本id，然后查询账单数据
			 */
			async getChartData() {
				await this.getAccountBookList();
				await this.init();
			},
			initMonth(callback) {
				this.currentTime = new Date();
				this.month = this.currentTime.getFullYear() + "-" + (this.currentTime.getMonth() + 1);
				if (callback) {
					callback();
				}
			},
			/**
			 * 切换月份，包含上下
			 */
			changeMonth(num) {
				var monthYearArr = this.month.split("-");
				if (Number(monthYearArr[1]) == 1 && num < 0) {
					this.month = (Number(monthYearArr[0]) - 1) + "-12";
				} else if (Number(monthYearArr[1]) == 12 && num > 0) {
					this.month = (Number(monthYearArr[0]) + 1) + "-1";
				} else {
					this.month = monthYearArr[0] + "-" + (Number(monthYearArr[1]) + num)
				}
				this.getChartData();
			},
			getLastMonth() {
			    var date = new Date();
			    var year = date.getFullYear();   //当前年：四位数字
			    var month = date.getMonth();     //当前月：0-11
			
			    if (month == 0) {   //如果是0，则说明是1月份，上一个月就是去年的12月
			        year -= 1;
			        month = 12;
			    }
			
			    month = month < 10 ? ('0' + month) : month;   //月份格式化：月份小于10则追加个0
			
			    let lastYearMonth = year + '-' + month;
			
			    return lastYearMonth;
			},
			/** 切换状态
			 * @param {Object} name flag名字
			 * @param {Object} flag 状态
			 */
			changeFlag(name, flag) {
				this[name] = flag;
			},
			/** 选中图标事件，改变显示图类型
			 * @param {Object} flag
			 */
			showChartPie (flag) {
				this.showPieChart = flag;
			},
			onPullDownRefresh() {
				this.getChartData();
				uni.stopPullDownRefresh();
			},
		}
	}
</script>

<style lang="scss">
	/* 设置背景颜色 */
	page {
		/* background-color: #fefdf8; */
		padding-top: var(--status-bar-height);
		background-color: $themeColor;
		box-sizing: border-box;
		width: 100vw;

	}

	.chart-container {
		padding: 35rpx;
		width: 100%;
		height: 100%;
		box-sizing: border-box;

		.tip-icon-container {
			width: 100%;
			height: 50rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.tip-left {
				width: 120rpx;
				height: 100%;
			}

			.inner-month-container {
				width: 60%;
				height: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.inner-month-container-last-month {
					width: 25%;
					height: 100%;
					display: flex;
					justify-content: flex-end;
					align-items: center;

					.inner-month-container-last-month-icon-bgc-container {
						width: 50rpx;
						height: 100%;
						border-radius: 50%;
						background-color: $themeBtnPurpleColor;
						display: flex;
						justify-content: center;
						align-items: center;
						color: $themePurpleColor;
						.inner-month-container-last-month-icon-item {
						}
					}
				}

				.inner-month-container-this-month {
					width: 40%;
					height: 100%;
					display: flex;
					justify-content: center;
					align-items: center;
				}

				.inner-month-container-next-month {
					width: 25%;
					height: 100%;
					display: flex;
					justify-content: flex-start;
					align-items: center;

					.inner-month-container-next-month-icon-bgc-container {
						width: 50rpx;
						height: 100%;
						border-radius: 50%;
						background-color: $themeBtnPurpleColor;
						display: flex;
						justify-content: center;
						align-items: center;
						color: $themePurpleColor;
						.inner-month-container-next-month-icon-item {

						}
					}
				}

			}

			.right-icon-container {
				width: 100rpx;
				height: 100%;
				display: flex;
				justify-content: center;
				align-items: center;
				.right-icon-container-type-icon-bgc-container {
					width: 100%;
					height: 100%;
					border-radius: 20rpx;
					background-color: $themeBtnPurpleColor;
					display: flex;
					justify-content: center;
					align-items: center;
					color: $themePurpleColor;

					.right-icon-date-content-icon {

					}

					.right-icon-container-type-icon-down-icon {
						// margin-left: 10rpx;
					}
				}
			}
		}

		.line-chart-container {
			width: 100%;
			height: 500rpx;
			margin-top: 20rpx;
			background-color: white;
			box-shadow: 0px 0px 2px #dfdede;
			border-radius: 20rpx;

			.charts-box {
				width: 100%;
				height: 500rpx;
			}
		}

		.pie-chart-container {
			width: 100%;
			height: 500rpx;
			background-color: white;
			box-shadow: 0px 0px 2px #dfdede;
			border-radius: 20rpx;
			margin-top: 20rpx;
			padding: 20rpx 20rpx;
			box-sizing: border-box;

			.pie-chart-title-container {
				width: 100%;
				height: 60rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.pie-chart-title-left-container {
					width: 50%;
					height: 100%;
					line-height: 60rpx;
				}

				.pie-chart-title-right-select-type {
					width: 50%;
					height: 100%;
					display: flex;
					justify-content: flex-end;
					align-items: center;
					font-size: 50rpx;
					color: $themeIconGreyColor;

					.pie-chart-title-right-select-type-pie {
						font-size: 50rpx;
						margin-right: 20rpx;
					}

					.pie-chart-title-right-select-type-bar {
						font-size: 50rpx;
						transform: rotate(90deg);
					}

					.icon-purple {
						color: $themePurpleColor;
					}
				}
			}

			.pie-charts-box {
				width: 100%;
				height: 440rpx;
			}

			.bar-charts-box {
				margin-top: 40rpx;
				width: 100%;
				height: 440rpx;
			}
		}

		.budget-bar-container {
			width: 100%;
			min-height: 50rpx;
			margin-top: 20rpx;
		}
	}
</style>